﻿using CodeGenerator.BaseUI;
using CodeGenerator.Common;
using CodeGenerator.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace CodeGenerator.UI
{
    /// <summary>
    /// Mybatis单表生成
    /// </summary>
    public partial class FrmCreateMybatisSingle : BaseFormEx
    {
        public FrmCreateMybatisSingle()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 后台任务
        /// </summary>
        BackgroundWorker doWork = null;
        /// <summary>
        /// 代码生成的内容
        /// </summary>
        Dictionary<string, string> content = new Dictionary<string, string>();
        /// <summary>
        /// 
        /// </summary>
        MybatisCodeCreate model = null;
        /// <summary>
        /// 表信息
        /// </summary>
        TableInfo tableInfo =new TableInfo();
       
        AutoSizeFormClass asc = new AutoSizeFormClass();

        private void FrmCreateBuildH_Load(object sender, EventArgs e)
        {
            asc.controllInitializeSize(this);

            ServerInfo server = Constant.CurrentServerInfo;
            if (server != null && !string.IsNullOrEmpty(Constant.DatabaseName))
            {
                IDatabase database = DBFactory.Database(server.DBType);

                string tableName = Constant.TableName;
                tableInfo.Name = tableName;

                tableInfo.Comments = database.GetTableComments(server,Constant.DatabaseName, tableName);
                tableInfo.ColumnList = database.GetColumnInfoList(server, server.DatabaseName, tableName);
               
            }

        }


        #region 按钮组
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            if (ucMybatisBasicControl1.Validate())
            {
                model = ucMybatisBasicControl1.GetBasicData();
                model.TableInfo = tableInfo;
                model.Name = model.TableInfo.Name;

                string[] prefixs = ucMybatisBasicControl1.Prefix.Split(',');
                foreach (var prefix in prefixs)
                {
                    if (!string.IsNullOrEmpty(prefix) && model.Name.Contains(prefix))
                    {
                        model.Name = model.TableInfo.Name.Replace(prefix, "");
                        break;
                    }
                }

                content.Clear();
                progressBar1.Visible = true;

                progressBar1.Minimum = 0;
                progressBar1.Maximum = 6;
                doWork = new BackgroundWorker();
                doWork.DoWork += doWork_DoWork;
                doWork.ProgressChanged += doWork_ProgressChanged;
                doWork.RunWorkerCompleted += doWork_RunWorkerCompleted;
                doWork.WorkerReportsProgress = true;//此属性必须设置，否则读取不到进度
                doWork.WorkerSupportsCancellation = true; // 运行取消操作;

                doWork.RunWorkerAsync();
            }
        }
        #endregion

        private void FrmCreateBuildH_SizeChanged(object sender, EventArgs e)
        {
            asc.controlAutoSize(this);
        }

        #region 开启工作
        void doWork_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //如果用户取消了当前操作就关闭窗口。
            if (e.Cancelled)
            {
                this.lblMsg.Text = "用户取消操作！！！";
            }
            else
            {
                this.lblMsg.Text = "执行完成！！！";
                doWork.CancelAsync();

                if (ucMybatisBasicControl1.Preview)
                {
                    FrmMybatisCode form1 = new FrmMybatisCode(content);
                    ((FrmMain)(this.ParentForm)).ShowContent(form1.Text, form1,true);
                }
            }
        }

        void doWork_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            //修改进度条的显示。
            this.progressBar1.Value = e.ProgressPercentage;

            string message = e.UserState.ToString();
            this.lblMsg.Text = message;
        }

        void doWork_DoWork(object sender, DoWorkEventArgs e)
        {
            //在操作的过程中需要检查用户是否取消了当前的操作。
            if (doWork.CancellationPending == true)
            {
                e.Cancel = true;
                return;
            }

            BackgroundWorker bgWorker = sender as BackgroundWorker;

            string entityTempletePath = "\\Template\\Mybatis\\Entity.cshtml";
            string daoTempletePath = "\\Template\\Mybatis\\Dao.cshtml";
            string mapperTempletePath = "\\Template\\Mybatis\\Mapper.cshtml";
            string iServiceTempletePath = "\\Template\\Mybatis\\IService.cshtml";
            string serviceTempletePath = "\\Template\\Mybatis\\Service.cshtml";

            bgWorker.ReportProgress(1, "正在生成实体类");
            string entityContent = RazorHelper.RunCompile(entityTempletePath, model);

            bgWorker.ReportProgress(2, "正在生成Dao类");
            string daoContent = RazorHelper.RunCompile(daoTempletePath, model);

            bgWorker.ReportProgress(3, "正在mapper文件");
            string mappingContent = RazorHelper.RunCompile(mapperTempletePath, model);

            bgWorker.ReportProgress(4, "正在生成Service接口类");
            string iServiceContent = RazorHelper.RunCompile(iServiceTempletePath, model);

            bgWorker.ReportProgress(5, "正在生成Service具体实现类");
            string serviceContent = RazorHelper.RunCompile(serviceTempletePath, model);



            if (!ucMybatisBasicControl1.Preview)
            {
                bgWorker.ReportProgress(6, "正在保存代码");

                string dirPath = ucMybatisBasicControl1.OutputDir + "\\Mybatis\\";

                List<string> list = new List<string>();
                list.Add(dirPath);
                list.AddRange(model.EntityPackage.Split('.'));
                list.Add(Utils.Pascal(model.Name) + ".java");
                string entityPath = Path.Combine(list.ToArray());

                list.Clear();
                list.Add(dirPath);
                list.AddRange(model.DaoPackage.Split('.'));
                list.Add(Utils.Pascal(model.Name) + "Dao.java");
                string daoPath = Path.Combine(list.ToArray());


                list.Clear();
                list.Add(dirPath);
                list.AddRange(model.Mapping.Split('.'));
                list.Add(Utils.Pascal(model.Name) + "Mapping.java");
                string mapperPath = Path.Combine(list.ToArray());

                list.Clear();
                list.Add(dirPath);
                list.AddRange(model.IServicePackage.Split('.'));
                list.Add(Utils.Pascal(model.Name) + "Service.java");
                string iServicePath = Path.Combine(list.ToArray());

                list.Clear();
                list.Add(dirPath);
                list.AddRange(model.ServicePackage.Split('.'));
                list.Add(Utils.Pascal(model.Name) + "ServiceImpl.java");
                string serviceDirPath = Path.Combine(list.ToArray());

                DirectoryUtil.Write(entityPath, entityContent);
                DirectoryUtil.Write(daoPath, daoContent);
                DirectoryUtil.Write(mapperPath, mappingContent);
                DirectoryUtil.Write(iServicePath, iServiceContent);
                DirectoryUtil.Write(serviceDirPath, serviceContent);

                System.Diagnostics.Process.Start(dirPath);
            }
            else
            {
                bgWorker.ReportProgress(6, "正在打开预览页");

                content.Add("entity", entityContent);
                content.Add("dao", daoContent);
                content.Add("mapper", mappingContent);
                content.Add("iservice", iServiceContent);
                content.Add("service", serviceContent);
            }
        }

        #endregion
    }
}
